package com.example.springstudy.controller;

import com.example.springstudy.base.Result;
import com.example.springstudy.base.annotation.DataScope;
import com.example.springstudy.base.annotation.SaveLog;
import com.example.springstudy.dao.dto.DeptDto;
import com.example.springstudy.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/dept")
public class DeptController {

    @Autowired
    DeptService deptService;

    @DataScope(deptAlias = "d")
    @GetMapping("/list")
    public Result<?> getDeptList(Integer pageNum, Integer pageSize) {
        return Result.success(deptService.listDept(pageNum, pageSize));
    }

    @GetMapping("/listAll")
    public Result<?> getDeptList() {
        return Result.success(deptService.allDept());
    }

    @SaveLog("更新部门")
    @PostMapping("/addOrUp")
    public Result<Boolean> addOrUpdate(@RequestBody DeptDto deptDto) {
        try{
            Assert.hasText(deptDto.getName(), "dept name must not be empty");
            Assert.hasText(deptDto.getCode(), "dept code must not be empty");
            return Result.success(deptService.addOrUpdateDept(deptDto));
        } catch (Exception e){
            return Result.failed(e.getMessage());
        }


    }

    @SaveLog("删除部门")
    @DeleteMapping("/delete")
    public Result<Boolean> delete(@RequestParam Integer deptId) {
        Assert.notNull(deptId, "deptId must not be null");
        return Result.success(deptService.deleteDept(deptId));
    }
}
